package com.cxlin.cwanandroid.ui.home.adapter

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseSingleItemAdapter
import com.chad.library.adapter4.util.getItemView
import com.cxlin.base.view.recyclerview.adapter.Handler
import com.cxlin.cwanandroid.R
import com.cxlin.cwanandroid.databinding.HeadViewBinding
import com.cxlin.cwanandroid.model.bean.Banner
import com.cxlin.cwanandroid.utils.GlideImageLoader
import com.youth.banner.BannerConfig

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/27 16:50
 */
class HeaderAdapter(val handler: Handler<Banner>) :
    BaseSingleItemAdapter<List<Banner>, HeaderAdapter.VH>() {

    private val banner: com.youth.banner.Banner? = null

    class VH(val binding: HeadViewBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
        val binding = DataBindingUtil.inflate<HeadViewBinding>(
            LayoutInflater.from(parent.context),
            R.layout.head_view, parent, false
        )
        return VH(binding)
    }

    override fun onBindViewHolder(holder: VH, item: List<Banner>?) {
        item?.let {
            val bannerImages = mutableListOf<String>()
            val bannerTitles = mutableListOf<String>()
            val bannerUrls = mutableListOf<String>()
            for (banner in it) {
                bannerImages.add(banner.imagePath)
                bannerTitles.add(banner.title)
                bannerUrls.add(banner.url)
            }
            holder.binding.banner.setImages(bannerImages)
                .setBannerTitles(bannerTitles)
                .setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)
                .setDelayTime(3000)
                .setImageLoader(GlideImageLoader())
                .setOnBannerListener { position ->
                    run {
                        handler.onClick(holder.binding.banner, it[position])
                    }
                }
            holder.binding.banner.start()
        }
    }

    fun startAutoPlay() {
        banner?.apply {
            startAutoPlay()
        }
    }

    fun stopAutoPlay() {
        banner?.apply {
            stopAutoPlay()
        }
    }

}